#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>

sem_t *m_sem[10]={0};
int thread_run = 1;

void *thread_timerfunc(void *argv)
{
	int count = 0;
	int sem_count = 0;
	while(1) {
		if (!(count%10))	//awake thread1 per 10s
			sem_post(m_sem[0]);
		sleep(1);
		count++;
	}
}

void *thread_func1(void *argv)
{
	int sem_count = 0;
	sem_t *thd_sem = (sem_t*)argv;
	while(thread_run) {
		sem_getvalue(thd_sem, &sem_count);
		if (sem_count != 0) {
			sem_wait(thd_sem);
			continue;
		}
		printf("thread_func1 begining!\n");
		sem_wait(thd_sem);
	}
	printf("thread end!\n");

}

int main()
{

	pthread_t ptd[10], ttd;
	
	//create timer thread
	pthread_create(&ttd, NULL, thread_timerfunc, (void*)NULL);
	
	//create a thread
	for (int i = 0; i < 1; i++) {
		m_sem[i] = malloc(sizeof(sem_t));
		sem_init(m_sem[i], 0, 0);
		pthread_create(&ptd[i], NULL, thread_func1, (void*)m_sem[i]);
	}
	while(1) {
		char c = getchar();
		if (c == 'e') {
			thread_run = 0;
			//pthread_join()
			//break;
		} else if (c == 'w') {
			for (int i = 0; i < 10; i++) {
				if (m_sem[i]) {
					sem_post(m_sem[i]);
				}
			}
		}
	}
	return 0;
}
